﻿using System.Diagnostics.Metrics;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Elastic.Clients.Elasticsearch;

namespace CICDk8s.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ArticleController: ControllerBase
    {
        private readonly ElasticsearchClient _client;

        public ArticleController(ElasticsearchClient elasticsearchClient)
        {
            _client = elasticsearchClient;
        }

        [HttpGet("Create")]
        public async Task<IActionResult> Create()
        {
            Article article = new Article()
            {
                Author = "11",
                Content = "测试",
                PostDate = DateTime.Now,
                Title = "主题"
            };
            var response = await _client.IndexAsync(article, "article");

            if (response.IsValidResponse)
            {
                return CreatedAtAction("Get", new { id = response.Id }, response);
            }

            return BadRequest();
        }

        [HttpGet("ArticleGet")]
        public async Task<IActionResult> Get(string id)
        {
            var response = await _client.GetAsync<Article>("article", id);

            if (response.IsValidResponse)
            {
                return Ok(response.Source);
            }

            return NotFound();
        }

        [HttpPost]
        public async Task<IActionResult> Update(string id, Article article)
        {
            var response =
                await _client.UpdateAsync<Article, Article>("article", id, descriptor => descriptor.Doc(article));

            if (response.IsValidResponse)
            {
                return Ok(response.SeqNo);
            }

            return BadRequest();
        }

        [HttpDelete]
        public async Task<IActionResult> Delete(string id)
        {
            var response =
                await _client.DeleteAsync("article", id);

            if (response.IsValidResponse)
            {
                return Ok(response.Result);
            }

            return BadRequest();
        }
    }
}
